package com.sample.hello2;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;

import com.swak.Constants;
import com.swak.OS;
import com.swak.exception.RemotingException;
import com.swak.reactivex.threads.Contexts;
import com.swak.reactivex.transport.Channel;
import com.swak.reactivex.transport.ExchangeChannel;
import com.swak.reactivex.transport.ExchangeHandlerAdapter;
import com.swak.reactivex.transport.ExchangeServer;
import com.swak.reactivex.transport.Exchangers;
import com.swak.reactivex.transport.Message;
import com.swak.reactivex.transport.TransportMode;
import com.swak.reactivex.transport.resources.LoopResources;
import com.swak.registry.URL;
import com.swak.utils.Maps;

/**
 * 一款服务器：主要测试quic协议
 * 
 * @author 618lf
 */
public class SampleServer extends ExchangeHandlerAdapter {

	private LoopResources resources = Contexts.createEventLoopResources(TransportMode.OS, 1, 2, "Sample.EventLoop-",
			false, 2, TimeUnit.SECONDS);

	ExchangeServer server;
	URL url;

	public SampleServer() throws RemotingException {
		Map<String, String> parameters = Maps.newHashMap();
		parameters.put(Constants.Bind_Host, Constants.ANYHOST);
		parameters.put(Constants.Use_Quic, "true");
		parameters.put(Constants.SSL_keyPath, "classpath:127.0.0.1+1-key.pem");
		parameters.put(Constants.SSL_certPath, "classpath:127.0.0.1+1.pem");
		this.url = new URL("Sample", OS.ip(), 10889, parameters);
		this.server = Exchangers.bind(url, resources, this);
	}

	/**
	 * 非请求数据，才会执行这个回调
	 */
	@Override
	public void received(Channel channel, Object message) throws RemotingException {
		System.out.println("收到数据， 或者 oneway 的请求！");
		channel.send(Message.forMessage().setData("服务器已经收到数据！"));
	}

	/**
	 * 收到请求数据时，会执行这个并返回响应数据
	 */
	@Override
	public CompletionStage<Object> reply(ExchangeChannel channel, Object message) throws RemotingException {
		System.out.println("收到请求，直接返回请求");
		return CompletableFuture.completedFuture(message);
	}
	
	@Override
	public void caught(Channel channel, Throwable exception) throws RemotingException {
		super.caught(channel, exception);
		System.out.println("异常处理");
		exception.printStackTrace();
	}

	/**
	 * 服务器启动
	 * 
	 * @param args
	 * @throws RemotingException
	 */
	public static void main(String[] args) throws RemotingException {
		new SampleServer();
	}
}
